package com.runfast.waimai.web.controller.base;

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.utils.ComUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * ${DESCRIPTION}  基本的权限
 *
 * @author chenzheng
 * @create 2018-05-07 11:45
 **/

@RestController("purviewController")
@RequestMapping("/server/purview")
public class PurviewController {
    @Autowired
    private BasePurviewService basePurviewService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Autowired
    private WaiMaiRunfastAgentaccountsService waiMaiRunfastAgentaccountsService;
    @Autowired
    private BaseRoleService baseRoleService;
    @Autowired
    private BaseUserRoleService baseUserRoleService;
    @Autowired
    private RunfastBusinessService runfastBusinessService;
    @Autowired
    private BaseRolePurviewService baseRolePurviewService;
    /*** 导航菜单*/
    @GetMapping("/menuList")
    public Result menuList(){
        List<BasePurview> menuList =new ArrayList<BasePurview>();
        BaseUser admin= SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        if(admin!=null && admin.getType()==1){
            //后台用户
            BaseUserRoleExample   example=new BaseUserRoleExample();
            example.createCriteria().andUseridEqualTo(admin.getId());
            List<BaseUserRole> baseUserRoleList=baseUserRoleService.selectByExample(example);
            if(baseUserRoleList.size()>0){
                menuList=selectBasePurviewsByRId(baseUserRoleList.get(0).getRid());
            }else{return Result.fail(null,"找不的此人对应的角色！");}
        }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            //代理商
            WaiMaiRunfastAgentbusiness agentBusiness = waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentAccounts.getAgentid());
              if (agentBusiness != null) {
                  menuList=selectBasePurviewsByRId(Integer.valueOf(agentAccounts.getByroles()));
              }else{return Result.fail(null,"找不到对应的代理商！");}
        }else if(admin!=null && admin.getType()==3 && accounts!=null){
            //商家用户
            RunfastBusiness business=runfastBusinessService.selectByPrimaryKey(accounts.getBusinessid());
            if(business!=null){
                menuList=selectBasePurviewsByRId(Integer.valueOf(accounts.getByroles()));
            }else{return Result.fail(null,"找不到对应的商家！");}
        }
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("menuList",menuList);
        return Result.ok(null,map);
    }
    /**根据角色id找到对应的权限list*/
    public  List<BasePurview> selectBasePurviewsByRId(Integer rId){
        List<BasePurview> menuList1 =new ArrayList<BasePurview>();
        BaseRolePurviewExample  example=new BaseRolePurviewExample();
        example.createCriteria().andRidEqualTo(rId);
        List<BaseRolePurview> baseRolePurviewList=baseRolePurviewService.selectByExample(example);
        if(baseRolePurviewList.size()>0){
           for(BaseRolePurview baseRolePurview:baseRolePurviewList){
               BasePurview purview=basePurviewService.selectByPrimaryKey(baseRolePurview.getPid());
               menuList1.add(purview);
           }
        }
        List<BasePurview> menuList=basePurviewService.parsePurview(menuList1);
        return menuList;
    }

    public void setRoles(String byroles,BaseUser user){
        if(!ComUtil.isEmpty(byroles)){
            BaseRole role = null;
            Set<BaseRole> roleList = new HashSet<BaseRole>();
            String[] strIds = byroles.split(",");
            //String[] strIds = "9".split(",");
            for(String strId:strIds){
                int rid = ComUtil.getInt(strId);
                if(rid>0){
                    role = baseRoleService.selectByPrimaryKey(rid);
                }
                if(role!=null){
                    roleList.add(role);
                    for(BasePurview pur:role.getPurviews()){
                        user.getPids().add(pur.getPid());
                    }
                }
            }
            user.setRoles(roleList);
        }
    }



    /**
     * 导航菜单-----------后续加入当前用户id
     */
    @GetMapping("/nav")
    public Result nav(){
        Integer userId=null;//当前登录用户的id
        //菜单
        List<BasePurview> purviewList = basePurviewService.getUserPurviewList(userId);
        //权限
        //Set<String> permissions = shiroService.getUserPermissions(userId);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("purviewList",purviewList);
        //map.put("permissions",permissions);
        return Result.ok(null,map);
    }

    /**
     * 所有菜单列表
     */
    @GetMapping("/list")
    //@RequiresPermissions("server:purview:list")
    public Result  list(){
        List<BasePurview> menuList = basePurviewService.selectByExample(null);
        for(BasePurview sysMenuEntity : menuList){
            BasePurview parentMenuEntity = basePurviewService.selectByPrimaryKey(sysMenuEntity.getByid());
            if(parentMenuEntity != null){
                sysMenuEntity.setParentName(parentMenuEntity.getPname());
            }
        }
        return Result.ok(null,menuList);
        //return menuList;
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    //@GetMapping("/select")
    //@RequiresPermissions("server:purview:select")
   /* public Result select(){
        //查询列表数据
        List<BasePurview> menuList = basePurviewService.queryNotButtonList();

        //添加顶级菜单
        BasePurview root = new BasePurview();
        root.setPid(0);
        root.setPname("一级菜单");
        root.setByid(-1);
        //root.setOpen(true);
        menuList.add(root);

        return Result.ok(null,menuList);
    }*/
    /**
     * 所有的权限一级二级
     * */
    @GetMapping("/select")
    public Result select(Integer agentId){
        BaseUser admin= SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentaccounts=SessionContext.getCurrentRunfastAgentaccounts();
        List<BasePurview> menuList1=null;
        List<BasePurview> menuList=null;
        if(admin!=null && admin.getType()==2 && agentaccounts!=null){
            List<Integer> list=new ArrayList<Integer>();
            if(agentaccounts.getByroles()!=null){
                list.add(Integer.valueOf(agentaccounts.getByroles()));
            }
            admin.setRoleIdList(list);
            menuList = basePurviewService.findForUser(admin,true);
        }else if(admin!=null && admin.getType()==1){
            if(agentId!=null){

                //WaiMaiRunfastAgentaccounts agentAccounts=waiMaiRunfastAgentaccountsService.selectByPrimaryKey(agentId);
                //if(agentAccounts!=null){
                    List<Integer> list=new ArrayList<Integer>();
                    //if(StringUtils.isNotBlank(agentAccounts.getByroles())){
                        list.add(12);
                    //}
                    admin.setRoleIdList(list);
                    menuList = basePurviewService.findForUser(admin,true);
                //}else{return Result.fail(null,"找不到对应的代理商账号！");}
            }else{
                menuList1 = basePurviewService.selectByExample(null);
                menuList=basePurviewService.parsePurview(menuList1);
            }
        }
        return Result.ok(null,menuList);
    }


    /**
     * 菜单信息
     */
    @GetMapping("/info")
    public Result info(Integer pid){
        BasePurview menu = basePurviewService.selectByPrimaryKey(pid);
        return Result.ok(null,menu);
    }

    /** 保存*/
    @PostMapping("/save")
    public Result save(@RequestBody BasePurview menu){
        if(menu!=null && StringUtils.isNotBlank(menu.getPname()) && (StringUtils.isNotBlank(menu.getLink()) || StringUtils.isNotBlank(menu.getIcon())) ){
            Integer  total=0;
            BasePurviewExample example=new BasePurviewExample();
            if(menu.getByid()==null){
                /**一级菜单*/
                menu.setByid(0);
                example.createCriteria().andByidEqualTo(0);
                total=basePurviewService.countByExample(example);
                menu.setSort(total);
            }else{
                /**二级菜单*/
                example.createCriteria().andByidEqualTo(menu.getByid());
                total=basePurviewService.countByExample(example);
                menu.setSort(total);
            }
            menu.setPtype(0);
            menu.setCreatetime(new Date());
            menu.setInfo(menu.getPname());
            basePurviewService.insert(menu);
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public Result update(@RequestBody BasePurview menu){
        if(menu!=null && menu.getPid()!=null &&StringUtils.isNotBlank(menu.getPname()) && (StringUtils.isNotBlank(menu.getLink()) || StringUtils.isNotBlank(menu.getIcon())) ){
            BasePurview purview=basePurviewService.selectByPrimaryKey(menu.getPid());
            if(purview!=null){
                if(purview.getByid()!=0){
                    //二级菜单
                    purview.setLink(menu.getLink());
                    purview.setPname(menu.getPname());
                    purview.setColor(menu.getColor());
                }else{
                    //一级菜单
                    purview.setPname(menu.getPname());
                    purview.setIcon(menu.getIcon());
                    purview.setLink(menu.getLink());
                    purview.setColor(menu.getColor());
                }
                basePurviewService.updateByPrimaryKeySelective(purview);
            }else{return Result.fail(null,"找不到对应的权限信息！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**
     * 删除---底层已经屏蔽后续看怎么处理
     */
    @PostMapping("/delete")
    //@RequiresPermissions("server:purview:delete")
    public Result delete(Integer pid){
        if(pid <= 31){
            return Result.fail(null,"系统菜单，不能删除");
        }

        //判断是否有子菜单或按钮
        List<BasePurview> menuList = basePurviewService.queryListParentId(pid);
        if(menuList.size() > 0){
            return Result.fail(null,"请先删除子菜单或按钮");
        }

        //basePurviewService.delete(pid);

        return Result.ok(null);
    }

    /**
     * 验证参数是否正确
     */
   /* private void verifyForm(BasePurview menu){
        if(StringUtils.isBlank(menu.getPname())){
            throw new RRException("菜单名称不能为空");
        }

     *//*   if(menu.getByid() == null){
            throw new RRException("上级菜单不能为空");
        }*//*

        //菜单
        *//*if(menu.getPtype() == Constants.MenuType.MENU.getValue()){
            if(StringUtils.isBlank(menu.getLink())){
                throw new RRException("菜单URL不能为空");
            }
        }*//*

        //上级菜单类型
       *//* int parentType = Constants.MenuType.CATALOG.getValue();
        if(menu.getByid() != 0){
            BasePurview parentMenu = basePurviewService.selectByPrimaryKey(menu.getByid());
            parentType = parentMenu.getPtype();
        }*//*

        //目录、菜单
       *//* if(menu.getPtype() == Constants.MenuType.CATALOG.getValue() ||
                menu.getPtype() == Constants.MenuType.MENU.getValue()){
            if(parentType != Constants.MenuType.CATALOG.getValue()){
                throw new RRException("上级菜单只能为目录类型");
            }
            return ;
        }

        //按钮
        if(menu.getPtype() == Constants.MenuType.BUTTON.getValue()){
            if(parentType != Constants.MenuType.MENU.getValue()){
                throw new RRException("上级菜单只能为菜单类型");
            }
            return ;
        }*//*
    }*/

}
